#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/time.h>

int main(int argc, char const *argv[])
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        perror("socket");
        exit(1);
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8015);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    int ret = bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if(ret == -1)
    {
        perror("bind");
        return -1;
    }

    ret = listen(fd, 5);
    if(ret == -1)
    {
        perror("listen");
        return -1;
    }

    // 设置超时时间
    struct timeval timeout;
    timeout.tv_sec = 60;
    timeout.tv_usec = 0;

    setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));

    // 等待客户端连接，60S内没有连接，则关闭服务器
    while(1)
    {
        struct sockaddr_in client_addr;
        socklen_t len = sizeof(client_addr);
        ret = accept(fd, (struct sockaddr *)&client_addr, &len);
        if(ret == -1)
        {
            printf("没有客户端连接，关闭服务器\n");
            close(fd);
            return 0;
        }
        else
        {
            printf("客户端%d连接\n", ret);
        }
    }
    return 0;
}
